package com.atguigu.es;

import org.apache.lucene.search.Query;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Iterator;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDataElasticSearchMainApplication.class)
public class SpringDataESSearchTest {

    @Autowired
    private ProductDao productDao;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Test
    public void termQuery() {

//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");
        //        Iterable<Product> search = productDao.search(termQueryBuilder);
        //        for (Product product : search) {
//            System.out.println(product);
//        }
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", "小米");

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(matchQueryBuilder);
        NativeSearchQuery build = nativeSearchQueryBuilder.build();
        SearchHits<Product> search = elasticsearchRestTemplate.search(build, Product.class);
        search.forEach(searchHit-> System.out.println(searchHit.getContent()));


    }

    /**
     * term 查询加分页
     */
    @Test
    public void termQueryByPage() {
//        int currentPage = 0;
//        int pageSize = 5;
//        //设置查询分页
//        PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");
//        Iterable<Product> products =
//                productDao.search2(termQueryBuilder, pageRequest);
//        for (Product product : products) {
//            System.out.println(product);
//        }


//        Iterable<Product> iterable = productDao.findAll();
//        iterable.forEach(System.out::println);
//        Iterator<Product> iterator = iterable.iterator();
//        while(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }

        Page<Product> page = productDao.findAll(PageRequest.of(0, 5));
        page.getContent().forEach(System.out::println);

    }
}

